package com.jxmobi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

/**
 * @author Xiaofei Chen <a href="mailto:xchen@jxmobi.com">Email the author</a>
 * @version 1.0 4/2/2016
 */
public class FunctionUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(FunctionUtils.class);

    public static <T,R> R transform(T t, Function<T, R> f) {
        return f.apply(t);
    }

    /**
     *  function compose to produce the result
     * @param t
     * @param transformers
     * @param <T>
     * @return
     */
    public static <T> T  transform2(T t, Function<T,T> ... transformers) {
        Function<T,T> composeFunction = composeAll(transformers);
        return transform(t, composeFunction);
    }

    /**
     *  combine all the functions together and return as a new function
     * @param functions All the functions
     * @param <T>
     * @return
     */
    public static <T> Function<T, T> composeAll(Function<T,T> ... functions) {
        List<Function<T,T>> functionList = Arrays.asList(functions);
        return functionList.stream().map(f -> f).reduce(Function.<T>identity(), (f, r) -> r.compose(f));
    }
}
